package com.alibaba.citrus.cr.common.config;

import com.alibaba.cz.base.tool.log.Log;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

/**
 * @author baizhuo
 * @version 1.0
 * @date 2023/8/30 10:51
 */
public class MdcTaskDecorator implements TaskDecorator {

    private static final Log log = Log.getLogger(MdcTaskDecorator.class);

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (null != copyOfContextMap) {
                    MDC.setContextMap(copyOfContextMap);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
